<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\model\general\LihuaStore;
use app\common\model\LihuaUseraddr;
use think\Exception;
use think\Validate;


/**
 * 收货地址
 */
class Useraddr extends Api
{
    protected $noNeedLogin = [];
    protected $noNeedRight = ['*'];

    /**
     * 地址管理
     *
     * @ApiMethod   (POST)
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     * @ApiReturn   ({"code":1,"msg":"OK","time":"1566863165","data":{"list":[{"id":260,"consignee":"王杰","mobile":"15261153531","address":"云山诗意12栋1901室","name":"云山诗意","house_num":"12栋1901室","lng":"119.914909","lat":"31.777077","store_id":0,"store_name":"怀南","city_id":0},{"id":263,"consignee":"陆陶然","mobile":"13776859705","address":"天宁区怡康花园8-乙-102","name":"","house_num":"","lng":"0.000000","lat":"0.000000","store_id":0,"store_name":"","city_id":0},{"id":264,"consignee":"马文毅","mobile":"13032502770","address":"常州市武进区长安家园二村12幢乙单元502室","name":"","house_num":"","lng":"0.000000","lat":"0.000000","store_id":0,"store_name":"","city_id":0}]}})
     */
    public function index()
    {
        $list = LihuaUseraddr::all(function ($query) {
            $query->where('user_id', $this->auth->id)->field('user_id', true);
        });
        $this->success('OK', ['list' => $list]);
    }

    /**
     * 查看地址
     *
     * @ApiMethod   (POST)
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     * @ApiParams   (name="id", type="string", required=true, description="地址id")
     * @ApiReturn   ({"code":1,"msg":"OK","time":"1566863303","data":{"id":260,"user_id":3,"consignee":"王杰","mobile":"15261153531","address":"云山诗意12栋1901室","name":"云山诗意1","house_num":"12栋1901室","lng":"119.914909","lat":"31.777077","store_id":0,"store_name":"怀南","city_id":0}})
     */
    public function info()
    {
        $id = (int)$this->request->post('id');
        if (!$id) $this->error('参数错误');

        $row = LihuaUseraddr::where(['id'=>$id, 'user_id'=>$this->auth->id])->find();
        if (!$row) $this->error('非法访问');

        $this->success('OK', $row);
    }

    /**
     * 新增地址
     *
     * @ApiMethod   (POST)
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     * @ApiParams   (name="consignee", type="string", required=true, description="收件人")
     * @ApiParams   (name="mobile", type="string", required=true, description="手机号")
     * @ApiParams   (name="address", type="string", required=true, description="地址详情")
     * @ApiParams   (name="name", type="string", required=true, description="地址名称")
     * @ApiParams   (name="house_num", type="string", required=true, description="门牌号")
     * @ApiParams   (name="lng", type="string", required=true, description="经度")
     * @ApiParams   (name="lat", type="string", required=true, description="纬度")
     * @ApiReturn   ({"code":1,"msg":"OK","time":"1567176439","data":{"id":373695,"user_id":3,"consignee":"李白","mobile":"13961259777","address":"湖塘烈帝路8888号","name":"聚湖雅苑","house_num":"16幢888号","lng":"119.951732","lat":"31.720689","store_id":18,"store_name":"湖塘","city_id":3}})
     */
    public function add()
    {
        $consignee = $this->request->post('consignee');
        $mobile    = $this->request->post('mobile');
        $address   = $this->request->post('address');
        $name      = $this->request->post('name');
        $house_num = $this->request->post('house_num');
        $lng       = $this->request->post('lng');
        $lat       = $this->request->post('lat');

        if (!$mobile || !$address || !$consignee || !$house_num || !is_numeric($lng) || !is_numeric($lat)) {
            if(!$consignee){ $this->error('请输入您的名称'); }
			if(!$mobile){ $this->error('手机号异常'); }
			if(!$address){ $this->error('请选择有效的地址'); }
			if(!$house_num){ $this->error('请输入您的门牌号'); }
			if(!is_numeric($lng) || !is_numeric($lat)){ $this->error('地址经纬度异常，请重新选择'); }
		};

        $len = mb_strlen($consignee);
        if ($len < 2 || $len > 12 ||
            !Validate::is($consignee, 'chs')) $this->error('姓名只允许2~12个汉字');

        if (!Validate::regex($mobile, "^1\d{10}$")) $this->error('手机号格式错误');

        $store = LihuaStore::getPointStore(0, $lng, $lat);
        if ($store['id'] == 0) $this->error('地址不在配送范围内');

        try {
            $addr = LihuaUseraddr::create([
                'user_id'    => $this->auth->id,
                'consignee'  => $consignee,
                'mobile'     => $mobile,
                'address'    => $address,
                'name'       => $name,
                'house_num'  => $house_num,
                'lng'        => $lng,
                'lat'        => $lat,
                'store_id'   => $store['id'],
                'store_name' => $store['name'],
                'city_id'    => $store['city_id'],
            ]);
        } catch (Exception $e) {
            $this->error('填写有误');
        }

        $this->success('OK', LihuaUseraddr::get($addr->id));
    }

    /**
     * 编辑地址
     *
     * @ApiMethod   (POST)
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     * @ApiParams   (name="id", type="string", required=true, description="地址id")
     * @ApiParams   (name="consignee", type="string", required=true, description="收件人")
     * @ApiParams   (name="mobile", type="string", required=true, description="手机号")
     * @ApiParams   (name="address", type="string", required=true, description="地址详情")
     * @ApiParams   (name="name", type="string", required=true, description="地址名称")
     * @ApiParams   (name="house_num", type="string", required=true, description="门牌号")
     * @ApiParams   (name="lng", type="string", required=true, description="经度")
     * @ApiParams   (name="lat", type="string", required=true, description="纬度")
     * @ApiReturn   ({"code":1,"msg":"OK","time":"1567176673","data":{"id":373694,"user_id":3,"consignee":"吴大帝","mobile":"13961259811","address":"中吴大道777号308","name":"金龙大厦","house_num":"15幢37号","lng":"119.951732","lat":"31.720689","store_id":18,"store_name":"湖塘","city_id":3}})
     */
    public function edit()
    {
        $id        = (int)$this->request->post('id');
        $consignee = $this->request->post('consignee');
        $mobile    = $this->request->post('mobile');
        $address   = $this->request->post('address');
        $name      = $this->request->post('name');
        $house_num = $this->request->post('house_num');
        $lng       = $this->request->post('lng');
        $lat       = $this->request->post('lat');

        // if (!$id || !$mobile || !$address || !$consignee || !$house_num || !is_numeric($lng) || !is_numeric($lat)) $this->error('参数错误');

        if (!$id || !$mobile || !$address || !$consignee || !$house_num || !is_numeric($lng) || !is_numeric($lat)) {
            if(!$id){ $this->error('参数错误'); }
            if(!$consignee){ $this->error('请输入您的名称'); }
			if(!$mobile){ $this->error('手机号异常'); }
			if(!$address){ $this->error('请选择有效的地址'); }
			if(!$house_num){ $this->error('请输入您的门牌号'); }
			if(!is_numeric($lng) || !is_numeric($lat)){ $this->error('地址经纬度异常，请重新选择'); }
		};

        $len = mb_strlen($consignee);
        if ($len < 2 || $len > 12 ||
            !Validate::is($consignee, 'chs')) $this->error('姓名只允许2~12个汉字');

        if (!Validate::regex($mobile, "^1\d{10}$")) $this->error('手机号格式错误');

        $store = LihuaStore::getPointStore(0, $lng, $lat);
        if ($store['id'] == 0) $this->error('地址不在配送范围内');

        try {
            LihuaUseraddr::update([
                'consignee'  => $consignee,
                'mobile'     => $mobile,
                'address'    => $address,
                'name'       => $name,
                'house_num'  => $house_num,
                'lng'        => $lng,
                'lat'        => $lat,
                'store_id'   => $store['id'],
                'store_name' => $store['name'],
                'city_id'    => $store['city_id'],
            ], ['id' => $id, 'user_id' => $this->auth->id]);
        } catch (Exception $e) {
            $this->error('填写有误');
        }

        $this->success('OK', LihuaUseraddr::get($id));
    }

    /**
     * 删除地址
     *
     * @ApiMethod   (POST)
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     * @ApiParams   (name="id", type="string", required=true, description="地址id")
     * @ApiReturn   ({"code":1,"msg":"OK","time":"1566500187","data":{}})
     */
    public function del()
    {
        $id = $this->request->post('id');
        if (!$id) $this->error('参数错误');

        $ret = LihuaUseraddr::where(['id' => $id, 'user_id' => $this->auth->id])->delete();
        if (!$ret) $this->error('删除失败');

        $this->success('OK');
    }

    /**
     * 选择地址
     *
     * @ApiMethod   (POST)
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     * @ApiParams   (name="store_id", type="int", required=true, description="门店id")
     * @ApiReturn   ({"code":1,"msg":"OK","time":"1567178760","data":{"inaddrs":[{"id":373694,"user_id":3,"consignee":"吴大帝","mobile":"13961259811","address":"中吴大道777号308","name":"金龙大厦","house_num":"15幢37号","lng":"119.951732","lat":"31.720689","store_id":18,"store_name":"湖塘","city_id":3},{"id":373695,"user_id":3,"consignee":"李白","mobile":"13961259777","address":"湖塘烈帝路8888号","name":"聚湖雅苑","house_num":"16幢888号","lng":"119.951732","lat":"31.720689","store_id":18,"store_name":"湖塘","city_id":3}],"outaddrs":[{"id":260,"user_id":3,"consignee":"王杰","mobile":"15261153531","address":"云山诗意12栋1901室","name":"","house_num":"","lng":"119.914909","lat":"31.777077","store_id":0,"store_name":"怀南","city_id":0},{"id":263,"user_id":3,"consignee":"陆陶然","mobile":"13776859705","address":"天宁区怡康花园8-乙-102","name":"","house_num":"","lng":"0.000000","lat":"0.000000","store_id":0,"store_name":"","city_id":0},{"id":264,"user_id":3,"consignee":"马文毅","mobile":"13032502770","address":"常州市武进区长安家园二村12幢乙单元502室","name":"","house_num":"","lng":"0.000000","lat":"0.000000","store_id":0,"store_name":"","city_id":0}]}})
     */
    public function sel()
    {
        $store_id = $this->request->post('store_id');
        if (!$store_id) $this->error('参数错误');

        $list = LihuaUseraddr::all(['user_id' => $this->auth->id]);
        $in = $out = [];
        foreach ($list as $k => $v) {
            if ($v['store_id'] == $store_id) {
                $in[]  = $v;
            } else {
                $out[] = $v;
            }
        }
        $this->success('OK', ['inaddrs' => $in, 'outaddrs' => $out]);
    }

}
